import {
	baseUrl
} from './config.js'

function http(url, data = {}, showLoading = false, method = 'GET', showMessage =
	true, header = {
		'content-type': 'application/json'
	}) {
	return new Promise((resolve, reject) => {
		if (showLoading) {
			uni.showLoading({
				mask: true,
				title: '拼命加载中...'
			})
		}
		if (uni.getStorageSync('uInfo') != '') {
			data.token = uni.getStorageSync('uInfo').token;
			data.phone = uni.getStorageSync('uInfo').phone;
			header.Authorization = uni.getStorageSync('uInfo').token;
		}
		uni.request({
			url: baseUrl + url,
			data: data,
			method: method,
			header: header,
			success(res) {
				uni.hideLoading()
				uni.stopPullDownRefresh()
				if (res.data.code == 0) {
					resolve(res.data);
				}else if (res.data.code == 1) {
					uni.showToast({
						title: res.data.msg ,
						icon: 'none',
						duration: 3000
					})
					resolve(res.data);
				}else if (res.data.code == 401) { 
				    uni.removeStorageSync('uinfo')
					setTimeout(function() {
						uni.navigateTo({
							url: '/pages/dengLu/dengLu'
						})
					}, 1500)
					return
				}else if (res.data.code == 403) {
					uni.showToast({
						title: res.data.msg || '连接服务器失败,请稍后重试!',
						icon: 'none',
						duration: 3000
					})
					// if (res.data.msg == '访问受限，请联系客服' ) {
						
					// } 
					return
				} else if (res.data.code == 406) {
					uni.showToast({
						title: res.data.msg || '连接服务器失败,请稍后重试!',
						icon: 'none',
						duration: 2000
					})
					setTimeout(function() {
						uni.switchTab({
							url: '/pages/woDe/woDe'
						})
					}, 1500)
					return
				} else if (res.data.code == 407) {
					uni.showToast({
						title: res.data.msg || '连接服务器失败,请稍后重试!',
						icon: 'none',
						duration: 3000
					})
					setTimeout(function() {
						uni.navigateTo({
							url: '/pages/shouye/shouye'
						})
					}, 1500)
					return
				} else if (res.data.code == 408) {
					uni.showToast({
						title: res.data.msg || '连接服务器失败,请稍后重试!',
						icon: 'none',
						duration: 3000
					})
					setTimeout(function() {
						uni.navigateTo({
							url: '/pages/shouye/shouye'
						})
					}, 1500)
					return
				} else {
					// token过期
					if (res.data.msg == '请先登录' || res.data.msg == '登录失效，重新登录') {
						uni.showToast({
							title: '登录失效，重新登录',
							icon: 'none',
							duration: 3000
						})
						uni.removeStorageSync('uinfo')
						setTimeout(function() {
							uni.navigateTo({
								url: '/pages/dengLu/dengLu'
							})
						}, 1500)
						return
					}
					if (showMessage) {
						uni.showToast({
							title: res.data.msg || '连接服务器失败,请稍后重试!',
							icon: 'none',
							duration: 3000
						})
					}


					reject(res.data)
				}
			},
			fail(res) {
				if (showMessage) {
					uni.showToast({
						title: '连接服务器失败,请稍后重试!',
						icon: 'none',
						duration: 3000
					})
				}
				uni.hideLoading()
			}
		})
	})

}
export default http;